

module.exports = {
    install: async router => {
        if (!router.$outside) return
        /** 查询单条 */
        router.get('/find', async (req, res) => {
            let db = await req.db(`SELECT * FROM ${router.$outside} WHERE ${router.$sortKey}=${req.query.id} ORDER BY ${router.$sortKey} ASC`);
            res.send(db[0])
        })

        /** 条件查询列表 */
        router.post('/list', async (req, res) => {
            let { pageSize = 10, pageNo = 1 } = req.body;
            pageNo = pageNo <= 1 ? 0 : pageNo - 1;
            let db = await req.db(`SELECT * FROM ${router.$outside} ORDER BY ${router.$sortKey} ASC LIMIT ${pageSize} OFFSET ${pageNo * pageSize}`);
            res.send(db);
        })

        /** 新增列表 */
        router.post('/add', async (req, res) => {
            let keys = Object.keys(req.body);
            let values = keys.map(item => {
                if (typeof req.body[item] == 'string') {
                    return JSON.stringify(req.body[item]);
                }
                return req.body[item];
            }).toString();
            await req.db(`INSERT INTO ${router.$outside} (${keys.toString()}) VALUES (${values})`)
            res.send({
                code: 200,
                msg: "新增成功"
            });
        })

        /** 删除列表 */
        router.delete('/del', async (req, res) => {
            await req.db(`DELETE FROM ${router.$outside} WHERE ${router.$sortKey}=${req.query.id}`)
            res.send({
                code: 200,
                msg: "删除成功"
            });
        });
        return;
    }
};